package com.hadoop.controller;

import com.hadoop.common.Constants;
import com.hadoop.component.CookieComponent;
import com.hadoop.dao.redis.RedisDao;
import com.hadoop.mybatis.po.User;
import com.hadoop.mybatis.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p></p>
 *
 * @author Andy
 * @date 2017/9/21
 */
@RequestMapping(value = "/web_hadoop")
@Controller
public class LoginController {
    @Resource
    private UserService userService;

    @Resource
    private RedisDao redisDao;

    @Resource
    private CookieComponent cookieComponent;

    @RequestMapping(value = "/login")
    public String login() {
        return "/sign_in/login";
    }

    @RequestMapping(value = "/login/post", method = RequestMethod.POST)
    public String loginPost(HttpServletRequest request, HttpServletResponse response, String userName, String password, Model model) {
        User user = null;

        if (StringUtils.isBlank(userName)) {
            return "forward:/web_hadoop/login";
        }

        if (StringUtils.isNotBlank(userName)) {
            user = userService.findUserByUserName(userName);
        }

        if (null == user) {
            model.addAttribute("msg", "此用户不存在，请注册。");
            return "redirect:/user/register";
        }

        String invalidKey = Constants.INVALID_USER_ID + user.getId();
        if (redisDao.isKeyExist(invalidKey)) {
            model.addAttribute("msg", "当前用户已被锁定，请管理员联系。");
            return "redirect:/web_hadoop/login";
        }

        if (StringUtils.isNotBlank(password)) {
            if (redisDao.isKeyExist(Constants.LOGIN_PASSWORD_ERROR_COUNT)) {
                int incrVal = NumberUtils.toInt(redisDao.readFromString(Constants.LOGIN_PASSWORD_ERROR_COUNT), 0);
                //如果当前用户三次以上密码错误，那么将当前用户进行禁止，不允许再登录，到时需要解绑才能使用。
                if (incrVal > 3) {
                    redisDao.incr(invalidKey);
                }
            }

            if (!StringUtils.equals(DigestUtils.md5Hex(password), user.getPassword())) {
                model.addAttribute("msg", "密码错误，请重新登录");
                redisDao.incr(Constants.LOGIN_PASSWORD_ERROR_COUNT);
                return "redirect:/web_hadoop/login";
            }
        }

        //将用户的信息写入到cookies中
        String cookiesVal = DigestUtils.md5Hex(Constants.COOKIE_KEY_WEB_HADOOP + ":" + user.getPhone() + ":" + user.getId());
        //写入cookie到用户浏览器
        response.addCookie(cookieComponent.createCookie(Constants.COOKIE_KEY_WEB_HADOOP, cookiesVal));

        String key = Constants.LOGIN_USER_INFO + cookiesVal;
        redisDao.writeRedisVoToHash(key, user);
        request.getSession().setAttribute("user",user);
        redisDao.setKeyExpire(key, Constants.SESSION_EXPIRE_TIME);
        return "/index";
    }

    @RequestMapping(value = "/login_out")
    public String loginOut(HttpServletRequest request,HttpServletResponse response) {
        //清除session
        request.getSession().removeAttribute("user");

        //清除Cookies
        Cookie cookie = cookieComponent.clearCookie(Constants.COOKIE_KEY_WEB_HADOOP);
        //写入cookie到用户浏览器
        response.addCookie(cookie);
        return "forward:/index";
    }
}
